package com.bhs.sansonglogistics.ui.home;

import static com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity.RC_LOCATION;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.ServiceSettings;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.AppDatabase;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.MyApplication;
import com.bhs.sansonglogistics.bean.Common;
import com.bhs.sansonglogistics.bean.Driver;
import com.bhs.sansonglogistics.bean.Location;
import com.bhs.sansonglogistics.bean.NewNotice;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.SocketBean;
import com.bhs.sansonglogistics.bean.event.ApplicationStatus;
import com.bhs.sansonglogistics.bean.event.Event;
import com.bhs.sansonglogistics.bean.event.ListeningStatus;
import com.bhs.sansonglogistics.bean.event.NewMessage;
import com.bhs.sansonglogistics.bean.event.OrderEvent;
import com.bhs.sansonglogistics.bean.event.PreemptStatus;


import com.bhs.sansonglogistics.bean.event.RefreshOrder;
import com.bhs.sansonglogistics.net.JWebSocketClient;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.serve.JWebSocketClientService;
import com.bhs.sansonglogistics.utils.CacheDataManager;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.StatusBarUtil;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.utils.VersionUpdatingUtils;
import com.bhs.sansonglogistics.utils.VoiceUtils;
import com.bhs.sansonglogistics.utils.WindowUtils;
import com.bhs.sansonglogistics.view.FloatWindow;
import com.bhs.sansonglogistics.view.GifView;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, NetCallBack {

    private ViewPager2 viewPage;
    private BottomNavigationView navView;
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private ChatMessageReceiver chatMessageReceiver;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            Location.latitude = aMapLocation.getLatitude();
            Location.longitude = aMapLocation.getLongitude();
            Location.city = aMapLocation.getCity();
        }
    };

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private FloatWindow floatWindow;
    private FrameLayout mFlReceiptReminder;
    private FrameLayout mFlOrder;
    private TextView mTvOrderNumber;
    private GifView mIvAnimation;
    private FrameLayout mFlHaveNewOrder;
    private int HowOrders = 0;
    private WindowUtils windowUtils;
    private BadgeDrawable badge;
    private BadgeDrawable mainBadge;
    private int mPosition;

    @Override
    public int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        //注册监听
        EventBus.getDefault().register(this);
        StatusBarUtil.setTranslucentStatus(this, true);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        viewPage = findViewById(R.id.view_page);
        navView = findViewById(R.id.nav_view);
        navView.setItemIconTintList(null);
        //蒲公英版本更新
        VersionUpdatingUtils.versionUpdating(mActivity);
        bindService();
        doRegisterReceiver();
        isOpenVoice = SharedPreferencesUtils.getBoolean(mActivity, "voice", true);
        //listeningList = SharedPreferencesUtils.getBoolean(mActivity, "isOpenListening", true);
        listeningList = true;
    }

    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            String hint;
//            if (requestCode == RC_WRITE_AND_READ_EXTERNAL_STORAGE) {
//                hint = "更新版本需要您的存储权限，请转到设置打开权限";
//            } else {
//                hint = "此功能需要开通位置权限来计算你和货主的距离，请转到设置打开权限";
//            }
//            new AppSettingsDialog.Builder(this).setTitle("提示").setRationale(hint).build().show();
//
//        }

    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            Common bean = new Gson().fromJson(json, Common.class);
            if (bean.isStatus()) {
                if (bean.getData().getNum() > 0) {
                    EventBus.getDefault().postSticky(new NewMessage("666"));
                    messageRed();
                }
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }


    /**
     * 广播消息 长连接消息
     */
    private class ChatMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            LogUtils.d(message);
            SocketBean socketBean = new Gson().fromJson(message, SocketBean.class);
            if (socketBean.getType().equals("init")) {
                networkRequest(netApi.bindClientId(socketBean.getClient_id()), MainActivity.this, 5);
            } else if (socketBean.getType().equals("order_new_order")) {
                HowOrders++;
                setFloatWindow();
                if (listeningList) {
                    EventBus.getDefault().post(socketBean.getData().getOrder_info());
                }
                if (SharedPreferencesUtils.getBoolean(mActivity, "banner", false) && listeningList) {
                    windowUtils.showPopupWindow(mActivity);
                    windowUtils.setData(socketBean.getData().getOrder_info());
                }
                redDot();
            } else if (socketBean.getType().equals("order_rob_result")) {
                if (HowOrders != 0) {
                    HowOrders--;
                    setFloatWindow();
                }
                OrderGoodsBean order_info = socketBean.getData().getOrder_info();
                //抢单状态
                int logistics_id = SharedPreferencesUtils.getInt(MyApplication.getContext(), "logistics_id", 0);
                if (order_info.getLogistics_id() == logistics_id) {
                    if (isOpenVoice) {
                        if (order_info.getDeliver_type() != 3) {
                            VoiceUtils.orderSuccess(mActivity);
                        } else {
                            VoiceUtils.orderReceiving(mActivity);
                        }
                    }
                    EventBus.getDefault().post(new PreemptStatus(order_info.getDeliver_sn(), order_info.getDeliver_type(), order_info.getOrder_type(), true));
                } else {
                    EventBus.getDefault().post(new PreemptStatus(order_info.getDeliver_sn(), order_info.getDeliver_type(), order_info.getOrder_type(), false));
                }

            } else if (socketBean.getType().equals("new_circle")) {
                messageRed();
                EventBus.getDefault().postSticky(new NewMessage("666"));
            }
        }
    }

    private void redDot() {
        if (mPosition != 0) {
            if (mainBadge == null) {
                mainBadge = navView.getOrCreateBadge(R.id.navigation_source_goods);
                mainBadge.setBackgroundColor(Color.parseColor("#FF6067"));
            } else {
                mainBadge.setVisible(true);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        registerReceiver(chatMessageReceiver, filter);
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(MainActivity.this, JWebSocketClientService.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            Log.e("hello", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //服务与活动断开
            Log.e("hello", "服务与活动成功断开");
        }
    };


    @Override
    public void initData() {
        viewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                navView.getMenu().getItem(position).setChecked(true);
            }
        });
        //禁止滑动
        viewPage.setUserInputEnabled(false);
        viewPage.setOffscreenPageLimit(5);//预加载五个 避免fragment销毁，重复创建
        viewPage.setAdapter(new FragmentAdapter(this));
        viewPage.setCurrentItem(0, false);
        navView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // 跳转指定页面：Fragment
                switch (item.getItemId()) {
                    case R.id.navigation_source_goods:
                        if (mainBadge != null) {
                            mainBadge.setVisible(false);
                        }
                        viewPage.setCurrentItem(0, false);
                        break;
                    case R.id.navigation_order_goods:
                        viewPage.setCurrentItem(1, false);
                        break;
                    case R.id.navigation_san_song:
                        viewPage.setCurrentItem(2, false);
                        break;
                    case R.id.navigation_message:
                        if (badge != null) {
                            badge.setVisible(false);
                        }
                        viewPage.setCurrentItem(3, false);
                        break;
                    case R.id.navigation_mine:
                        viewPage.setCurrentItem(4, false);
                        break;

                }
                return false;
            }
        });
        viewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mPosition = position;
                if (position == 1) {
                    EventBus.getDefault().post(new RefreshOrder(""));
                }
            }
        });
        floatWindow();
        CacheDataManager.clearAllCache(this);
        networkRequest(netApi.get_new_circle_num(SharedPreferencesUtils.getInt(mActivity, "logistics_id", 0)), this);
    }


    public void floatWindow() {
        windowUtils = new WindowUtils();
        //悬浮窗
        floatWindow = new FloatWindow(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_float_window, null);
        mFlReceiptReminder = view.findViewById(R.id.fl_receipt_reminder);
        mFlOrder = view.findViewById(R.id.fl_order);
        mTvOrderNumber = view.findViewById(R.id.tv_order_number);
        mIvAnimation = view.findViewById(R.id.iv_animation);
        mFlHaveNewOrder = view.findViewById(R.id.fl_have_new_order);
        floatWindow.setLayout(view);
        floatWindow.setOnFloatListener(new FloatWindow.FloatClickListener() {
            @Override
            public void onFloatClick(View v) {
                startActivity(new Intent(mActivity, MainActivity.class));
                EventBus.getDefault().post(new Event(0));
            }
        });
    }

    @Subscribe
    public void onEvent(Event event) {
        viewPage.setCurrentItem(event.getType());
    }

    @Subscribe
    public void onEvent(OrderEvent event) {
        HowOrders = event.orderNumber;
        setFloatWindow();
    }

    //新消息给个小红点
    @Subscribe
    public void onEvent(NewMessage event) {
        messageRed();
    }

    private void messageRed() {
        if (mPosition != 3) {
            if (badge == null) {
                badge = navView.getOrCreateBadge(R.id.navigation_message);
                badge.setBackgroundColor(Color.parseColor("#FF6067"));
            } else {
                badge.setVisible(true);
            }
        }
    }

    //新通知给个小红点
    @Subscribe
    public void onEvent(NewNotice event) {
        messageRed();
    }

    @SuppressLint("SetTextI18n")
    private void setFloatWindow() {
        if (HowOrders > 0) {
            mIvAnimation.setVisibility(View.GONE);
            mFlOrder.setVisibility(View.VISIBLE);
            mFlHaveNewOrder.setVisibility(View.VISIBLE);
        } else {
            mIvAnimation.setVisibility(View.VISIBLE);
            mFlOrder.setVisibility(View.GONE);
            mFlHaveNewOrder.setVisibility(View.GONE);
        }
        mTvOrderNumber.setText(String.valueOf(HowOrders));
    }

    @Subscribe
    public void onEvent(ApplicationStatus event) {
        if (SharedPreferencesUtils.getBoolean(mContext, "floatingWindow", false) && listeningList) {
            if (event.isBackstage()) {
                if (!floatWindow.isShow() && !isOut) {
                    floatWindow.show();
                }
            }
        }

        if (!event.isBackstage() && floatWindow.isShow()) {
            floatWindow.close();
        }
    }

    static class FragmentAdapter extends FragmentStateAdapter {
        public FragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position) {
                case 0:
                    return SourceGoodsFragment.newInstance();
                case 1:
                    return OrderGoodsFragment.newInstance();
                case 2:
                    return SanSongFragment.newInstance();
                case 3:
                    return MessageFragment.newInstance();
                default:
                    return MineFragment.newInstance();

            }
        }

        @Override
        public int getItemCount() {
            return 5;
        }
    }

    private boolean listeningList;//是否听单
    private boolean isOpenVoice;//是否开启声音
    private boolean isOut;//是否是退出程序

    @Subscribe
    public void onEvent(ListeningStatus event) {
        listeningList = event.isListeningList();
        isOpenVoice = event.isOpenVoice();
        if (floatWindow.isShow() && !listeningList) {
            floatWindow.close();
        }
//        if (listeningList) {
//            methodRequiresTwoPermission();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        jWebSClientService = null;
        unbindService(serviceConnection);
        unregisterReceiver(chatMessageReceiver);
        closeConnect();
    }

//    @Subscribe
//    public void onEvent(CloseConnect event) {
//        jWebSClientService = null;
//        unbindService(serviceConnection);
//        unregisterReceiver(chatMessageReceiver);
//        closeConnect();
//    }


    /**
     * 断开连接
     */
    private void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }


    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            if (mLocationClient == null) {
                //初始化定位
                try {
                    mLocationClient = new AMapLocationClient(getApplicationContext());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //设置定位回调监听
                mLocationClient.setLocationListener(mLocationListener);
                //初始化AMapLocationClientOption对象
                mLocationOption = new AMapLocationClientOption();

                AMapLocationClientOption option = new AMapLocationClientOption();
                /**
                 * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
                 */
                option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
                if (null != mLocationClient) {
                    mLocationClient.setLocationOption(option);
                    //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                    mLocationClient.stopLocation();
                    mLocationClient.startLocation();
                }

                //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//            //获取一次定位结果：
//            //该方法默认为false。
//            mLocationOption.setOnceLocation(true);
                //获取最近3s内精度最高的一次定位结果：
                //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
                mLocationOption.setOnceLocationLatest(true);
                //给定位客户端对象设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
                //启动定位
                mLocationClient.startLocation();
            }
        } else {
            if (!SharedPreferencesUtils.getBoolean(mActivity, "isFirst", false)) {
                SharedPreferencesUtils.saveBoolean(mActivity, "isFirst", true);
                new XPopup.Builder(mActivity)
                        .asConfirm("提示", "我需要您的位置信息来计算货物距离",
                                "取消", "确定",
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        // Do not have permissions, request them now
                                        EasyPermissions.requestPermissions(MainActivity.this, "我需要您的位置信息来计算货物距离",
                                                RC_LOCATION, perms);
                                    }
                                }, null, false)
                        .show();
            } else {
                EasyPermissions.requestPermissions(MainActivity.this, "我需要您的位置信息来计算货物距离",
                        RC_LOCATION, perms);
            }
        }
    }


    private long exitTime;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.show("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            MobclickAgent.onKillProcess(MyApplication.getContext());
            isOut = true;
            finish();
        }
    }

}